package com.dkd.sbtz.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.dkd.common.core.domain.R;
import com.dkd.common.utils.SecurityUtils;
import com.dkd.common.utils.ServletUtils;
import com.dkd.sbtz.domain.AssetMtplanSpare;
import com.dkd.sbtz.domain.mtplan.MtplanSpareHistoryVO;
import com.dkd.sbtz.domain.plando.MtPlanDetailVO;
import com.dkd.sbtz.domain.plando.MtPlanListRow;
import com.dkd.sbtz.domain.plando.MtPlanQueryReq;
import com.dkd.sbtz.domain.plando.PageResult;
import com.dkd.sbtz.domain.vo.MtPlanCreateReq;
import com.dkd.sbtz.domain.vo.PlanQuery;
import com.dkd.sbtz.domain.vo.spare.SpecialItemDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.dkd.common.annotation.Log;
import com.dkd.common.core.controller.BaseController;
import com.dkd.common.core.domain.AjaxResult;
import com.dkd.common.enums.BusinessType;
import com.dkd.sbtz.domain.AssetMtplan;
import com.dkd.sbtz.service.IAssetMtplanService;
import com.dkd.common.utils.poi.ExcelUtil;
import com.dkd.common.core.page.TableDataInfo;

/**
 * 设备计划维护Controller
 * 
 * @author xzj
 * @date 2025-09-19
 */
@RestController
@RequestMapping("/sbtz/mtplan")
@RequiredArgsConstructor
public class AssetMtplanController extends BaseController
{
    @Autowired
    private final IAssetMtplanService assetMtplanService;

    /** 列表（按 assetId 等） */
    @PreAuthorize("@ss.hasPermi('sbtz:mtplan:list')")
    @GetMapping("/list")
    public TableDataInfo list(AssetMtplan query) {
        startPage();
        List<AssetMtplan> list = assetMtplanService.selectAssetMtplanList(query);
        return getDataTable(list);
    }

    /** 详情（按 planId） */
    @PreAuthorize("@ss.hasPermi('sbtz:mtplan:query')")
    @GetMapping("/getdetail/{planId}")
    public AjaxResult getInfo(@PathVariable Long planId) {
        return AjaxResult.success(assetMtplanService.selectAssetMtplanDetail(planId));
    }

    /** 新增（可带 spares） */
    @PreAuthorize("@ss.hasPermi('sbtz:mtplan:add')")
    @Log(title = "设备计划维护", businessType = BusinessType.INSERT)
    @PostMapping("/createplan")
//    public AjaxResult add(@RequestBody AssetMtplan po) {
//        return toAjax(assetMtplanService.insertAssetMtplan(po));
//    }
    public AjaxResult create(@RequestBody AssetMtplan dto) {
        Long id = assetMtplanService.createPlan(dto);
        return success(id);
    }

    /** 修改主表 */
    @PreAuthorize("@ss.hasPermi('sbtz:mtplan:edit')")
    @Log(title = "设备计划维护", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AssetMtplan po) {
        return toAjax(assetMtplanService.updateAssetMtplan(po));
    }


    @PreAuthorize("@ss.hasPermi('sbtz:mtplan:query')")
    @GetMapping("/{planId}/spares")
    public AjaxResult getSpares(@PathVariable Long planId) {
        return AjaxResult.success(assetMtplanService.selectPlanSpares(planId));
    }

    /** 全量替换备件（编辑页保存） */
    @PreAuthorize("@ss.hasPermi('sbtz:mtplan:edit')")
    @Log(title = "设备计划-备件清单", businessType = BusinessType.UPDATE)
    @PutMapping("/{planId}/spares")
    public AjaxResult replaceSpares(@PathVariable Long planId, @RequestBody List<AssetMtplanSpare> spares) {
        assetMtplanService.replacePlanSpares(planId, spares);
        return AjaxResult.success();
    }


    /**
     * 替换某计划的「特殊（采购）备件」清单
     * - 前端传空数组 [] 表示清空
     */
    @PreAuthorize("@ss.hasPermi('sbtz:mtplan:edit')")
    @Log(title = "计划-特殊备件替换", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/{id}/spares/special", consumes = "application/json")
    public AjaxResult replacePlanSpecialSpares(@PathVariable("id") Long planId,
                                               @RequestBody(required = false) List<SpecialItemDTO> items) {
        assetMtplanService.replacePlanSpecialSpares(planId, items);
        return success();
    }

    /** 删除（逻辑删除 deleted=1） */
//    @PreAuthorize("@ss.hasPermi('sbtz:mtplan:remove')")
//    @Log(title = "设备计划维护", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{ids}")
//    public AjaxResult remove(@PathVariable Long[] ids) {
//        return toAjax(assetMtplanService.deleteAssetMtplanByIds(ids));
//    }



    @PreAuthorize("@ss.hasPermi('sbtz:mtplan:remove')")
    @Log(title = "维保计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(assetMtplanService.deletePlanCascade(ids));
    }

    @PreAuthorize("@ss.hasPermi('sbtz:mtplan:edit')")
    @Log(title = "设备计划维护", businessType = BusinessType.UPDATE)
    @PutMapping("/updateplan/{id}")
    public AjaxResult updatePlanFields(@PathVariable Long id, @RequestBody AssetMtplan dto) {
        dto.setId(id);                                 // 以路径中的 id 为准
        dto.setUpdateBy(SecurityUtils.getUsername());  // 若依：记录更新人
        int rows = assetMtplanService.updatePlanFields(dto);
        return toAjax(rows);
    }


    @PreAuthorize("@ss.hasPermi('sbtz:mtplan:history')")
    @GetMapping("/history/{assetId}")
    public TableDataInfo history(@PathVariable Long assetId,
                                 @RequestParam(required = false) Long planId,
                                 @RequestParam(required = false) String keyword) {
        startPage(); // 读取 pageNum/pageSize

        String beginTime = ServletUtils.getParameter("params[beginTime]");
        String endTime   = ServletUtils.getParameter("params[endTime]");

        List<MtplanSpareHistoryVO> list =
                assetMtplanService.selectHistory(assetId, planId, keyword, beginTime, endTime);
        return getDataTable(list);
    }

}
